package summer.backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution93 {
    List<String> res = new ArrayList<>();
    List<String> tmp = new LinkedList<>();

    public List<String> restoreIpAddresses(String s) {
        backtracking(s, 0);
        return res;
    }

    public void backtracking(String s, int index) {
        if (tmp.size() == 4) {
            if (index == s.length()) {
                StringBuffer sb = new StringBuffer();
                for (String cur : tmp) {
                    sb.append(cur).append(".");
                }
                sb.deleteCharAt(sb.length() - 1);
                res.add(sb.toString());
            }
            return;
        }

        for (int i = index; i < s.length(); i++) {
            String curStr = s.substring(index, i + 1);
            if (!isIP(curStr)) continue;
            tmp.add(curStr);
            backtracking(s, i + 1);
            tmp.remove(tmp.size() - 1);
        }
    }

    public boolean isIP(String IP) {
        if (IP.length() > 1 && IP.charAt(0) == '0') return false;
        if (IP.length() > 3) return false;
        int num = Integer.parseInt(IP);
        return num >= 0 && num <= 255;
    }
}
